package com.nanyang.tms.controller.handler;


import com.nanyang.common.core.dict.CommonEnum;
import com.nanyang.common.core.domain.ApiResult;
import com.nanyang.common.core.exception.ServiceException;
import com.nanyang.common.tool.utils.json.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler{


	public static final String X_REQUESTED_WIDTH="X-Requested-With";
	public static final String XML_HTTP_REQUEST="XMLHttpRequest";

	
	@SuppressWarnings("rawtypes")
	@ResponseStatus()
	@ExceptionHandler(value=Exception.class)
	public ApiResult handleException(HttpServletRequest request, HttpServletResponse response, Exception e){
		log.error("Path:"+request.getRequestURI());
		log.error("Param:"+ JsonUtil.toJson(request.getParameterMap()));
		log.error("Exception:",e);
		ApiResult apiResult=new  ApiResult();
		apiResult.setCode(500);
		apiResult.setMessage(e.getLocalizedMessage());
    	return apiResult;
	}
	@SuppressWarnings("rawtypes")
	@ResponseStatus()
	@ExceptionHandler(value= ServiceException.class)
	public    ApiResult handleServiceException(HttpServletRequest request,HttpServletResponse response,ServiceException e){
		log.error("Path:"+request.getRequestURI());
		log.error("Param:"+JsonUtil.toJson(request.getParameterMap()));
		log.error("ServiceExceptionException:",e);
		ApiResult apiResult=new  ApiResult();
		apiResult.setCode(e.getCode());
		apiResult.setMessage(e.getMessage());
	    return apiResult;  
	}
	@SuppressWarnings("rawtypes")
	@ExceptionHandler(value=MethodArgumentNotValidException.class)
	public    ApiResult handleException(HttpServletRequest request,HttpServletResponse response,MethodArgumentNotValidException e){
		BindingResult bindingResult = e.getBindingResult();

	       String errorMesssage = "参数校验错误:";

	       for (FieldError fieldError : bindingResult.getFieldErrors()) {
	           errorMesssage += fieldError.getDefaultMessage() + ", ";
	       }
	       ApiResult apiResult=new  ApiResult();
			apiResult.setCode(CommonEnum.ARG_NOTVALID.getCode());
			apiResult.setMessage(String.format(CommonEnum.ARG_NOTVALID.getMessage(), errorMesssage));
	       return apiResult;
	}
	
	  
}
